#!/usr/bin/python
################################################################################
## DATE: 2010-08-26
## AUTHOR: Matt Reid
## WEBSITE: http://kontrollsoft.com
## EMAIL: support@kontrollsoft.com
## LICENSE: BSD http://www.opensource.org/licenses/bsd-license.php
################################################################################
## Copyright 2010-present Matt Reid
## All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##################################################################################
## WHAT THIS SCRIPT DOES #########################################################

##################################################################################
from __future__ import division
from socket import gethostname;
import threading
import socket
import sys
import os
import urllib
import urllib2
import commands
import select
import getopt
import logging
import MySQLdb
import datetime
import time
import array
import random
import string
from ConfigParser import ConfigParser

ver = sys.version.split(' ')[0].split(".")
major=ver[:1]
minor=ver[1:2]
version="%s.%s"%(major[0],minor[0])
if version in ('2.4','2.3','2.2','2.1','2.0'):
    pyver = "old"
else:
    pyver = "new"

chost = gethostname()
now = datetime.datetime.now()

def print_help():
    print '''
dbbenchmark.py - the database benchmarking tool
==================================================
Date: 2010-08-26
Website: http://dbbenchmark.com
Author: Matt Reid
Email: mreid@kontrollsoft.com
License: new BSD license
==================================================
Use the following flags to change default behavior
    
   Option                 Description
   --mysql-host=          MySQL hostname
   --mysql-user=          MySQL username
   --mysql-pass=          MySQL password
   --mysql-port=          MySQL port
   --mysql-db=            MySQL database
   --mysql-timeout=       MySQL socket timeout
   --mysql-no-tx          MySQL transaction disable
   --insert-quant=        INSERT quantity for benchmark, default 1000
   --select-quant=        SELECT quantity for benchmark, default 100
   --select_no_index_off  Disable benchmark for SELECTs without INDEXes
   --threads=             Number of threads for query execution (default 4)
   --update-url=          URL to send benchmark data to (other than default)
   --print-sql            Print SQL creation for test schema
   --help                 Print this message
   '''

def print_sql():
    print '''CREATE DATABASE dbbench;
USE dbbench;

CREATE TABLE `dbbench` (
`id` BIGINT(64) UNSIGNED NOT NULL auto_increment,
`A` BIGINT(64) UNSIGNED NOT NULL DEFAULT '0',
`B` CHAR(255) NOT NULL DEFAULT '',
`C` CHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY  (`id`),
KEY `B_ix` (`B`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

grant all on dbbench.* to 'dbbench'@'localhost' identified by 'dbbench';
'''

def strrep(str):
    rep = [ ",","\r","\n","(",")","$","%","^","&","*","+","!","=","~","`","{","}","[","]","|","?","<",">","@"]
    for r in rep:
        str = str.replace(r,'')
    str = str.replace(' ','-')
    str = str.strip()
    return str

def logger(detail,level):
    if(level == "d"):
        log.debug("%s"% (detail))
    elif(level == "i"):
        log.info("%s"% (detail))
    elif(level == "w"):
        log.warn("%s"% (detail))
    elif(level == "e"):
        log.error("%s"% (detail))
    elif(level == "c"):
        log.critical("%s"% (detail))
    
class threader(threading.Thread):
    def __init__(self,method,tx,db):
        threading.Thread.__init__(self)
        self.tx = tx
        self.method = method
        self.db = db
    def run(self):
        if self.method == "insert":
            for i in range(insert_quant):
                run_insert(self.tx,i,self.db)
        else:
            s_quant = int(select_quant / 2)
            for i in range(s_quant):
                run_select(self.method,self.db) 
        
def randstr(length):
    twoletters = [c+d for c in string.letters for d in string.letters]
    r = random.random
    n = len(twoletters)
    l2 = length//2
    lst = [None] * l2
    for i in xrange(l2):
        lst[i] = twoletters[int(r() * n)]
        if length & 1:
            lst.append(random.choice(string.letters))

    return "".join(lst)

def run_insert(tx,range,db):
    str0 = randstr(254)
    str1 = randstr(254)
    if tx == 0: #no transactions
        sql = "INSERT INTO dbbench (`id`,`A`,`B`,`C`) VALUES (NULL,'%i','%s','%s');"%(range,str0,str1)
        try:
            cursor = db.cursor()
            cursor.execute(sql)
        except:
            print "insert failed"
            
    elif tx == 1: #use transactions
        sql = "INSERT INTO dbbench (`id`,`A`,`B`,`C`) VALUES (NULL,'%i','%s','%s');"%(range,str0,str1)
        try:
            cursor = db.cursor()
            cursor.execute(sql)
            db.commit() 
        except:
            print "insert failed"

def run_select(type,db):
    #random indexed 
    sql_index_rand = "SELECT A,B,C FROM dbbench FORCE INDEX (B_ix) ORDER BY rand() LIMIT 1;"
    sql_index_seq = "SELECT id,A,B,C FROM dbbench FORCE INDEX (B_ix) ORDER BY A LIMIT 1;"

    #non indexed select - NOTE: I/O heavy as the row count increases
    sql_noindex_rand = "SELECT A,B,C FROM dbbench IGNORE INDEX (B_ix) ORDER BY rand() LIMIT 1;"
    sql_noindex_seq = "SELECT A,B,C FROM dbbench IGNORE INDEX (B_ix) ORDER BY A LIMIT 1;"

    if type == "select_index_yes_rand":
        sql = sql_index_rand
    elif type == "select_index_yes_seq":
        sql = sql_index_seq
    elif type == "select_index_no_rand":
        sql = sql_noindex_rand
    elif type == "select_index_no_seq":
        sql = sql_noindex_seq
    try:
        cursor = db.cursor()
        cursor.execute(sql)
        db.commit()
    except:
        print "select failed"
            
def system_command(cmd):
    start = datetime.datetime.now()
    retcode, output = commands.getstatusoutput(cmd)
    end = datetime.datetime.now()
    timing = end - start
    logger("Total compute time: %s"%(timing),'d')
    if retcode != 0:
        retcode = str(retcode)
        print retcode
        sys.exit(1)
    else:
        return output

def closedb():    
    id=0
    for db in connections:
        try:
            db.close()
            logger("DB connection closed for thread: %i."%(id),"i")            
            id+=1
        except MySQLdb.Error, e:
            logger("DB connection close for thread: %i: %d: %s"%(id,e.args[0], e.args[1]),"i")
            id+=1

def check_port(port):
    socktime = float(mysql_socket_timeout)
    host= mysql_host
    socket.setdefaulttimeout(socktime) 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, int(port)))
        s.shutdown(2)
        return 0
    except:
        logger("Could not connect to MySQL via host/port: %s/%s"%(mysql_host,mysql_port),"i")
        sys.exit(1)

def init_thread(method,tx):    
    backgrounds = []
    for db in connections:
        logger("Spawning thread: %s"%(db),"d")
        quant = tx / THREADS
        background = threader(method,quant,db)        
        background.start()
        backgrounds.append(background)
    for background in backgrounds:
        background.join()

def main():    
    test = "truncate table dbbench;"
    try:
        cursor = initdb.cursor()
        cursor.execute(test)
    except:
        logger("Truncate table failed.","i")
        sys.exit(1)

    #record info
    sql_version = "show global variables like 'version'"
    sql_innodb_buffer_pool = "show global variables like 'innodb_buffer_pool_size'"
    sql_sync_binlog = "show global variables like 'sync_binlog'"
    sql_tx_isolation = "show global variables like 'tx_isolation'"
    sql_innodb_flush_tx = "show global variables like 'innodb_flush_log_at_trx_commit'"

    cursor.execute(sql_version)    
    MYSQL_VERSION = strrep(cursor.fetchone()[1]) #we get ('version')('5.0.0.etc')  and convert to 5.0.0.etc
    cursor.execute(sql_innodb_buffer_pool)
    MYSQL_INNODB_BUFFER_POOL_SIZE = cursor.fetchone()[1]
    cursor.execute(sql_sync_binlog)
    MYSQL_SYNC_BINLOG = cursor.fetchone()[1]
    cursor.execute(sql_tx_isolation)
    MYSQL_TX_ISOLATION = strrep(cursor.fetchone()[1])
    cursor.execute(sql_innodb_flush_tx)
    MYSQL_INNODB_FLUSH_TX = strrep(cursor.fetchone()[1])

    SYSTEM_KERNEL = strrep(system_command("uname -r"))
    SYSTEM_ARCH = strrep(system_command("uname -m"))
    SYSTEM_OS = strrep(system_command("uname -s"))
    if SYSTEM_OS == "Linux":
        #cpu_out = system_command("cat /proc/cpuinfo |grep 'model name'|awk -F\: {'print $2'}")
        CPU_MODEL = strrep(system_command("cat /proc/cpuinfo |grep 'model name'|awk -F\: {'print $2'}|tail -n 1").strip())
        CPU_SPEED = round(float(strrep(system_command("cat /proc/cpuinfo |grep 'cpu MHz'|awk -F\: {'print $2'}|tail -n 1").strip())))
        MEMORY_TOTAL_BYTES = (int(system_command("cat /proc/meminfo |grep MemTotal|awk -F\: {'print $2'}|awk {'print $1'}"))) * 1024
        MEMORY_FREE_BYTES = (int(system_command("cat /proc/meminfo |grep MemFree|awk -F\: {'print $2'}|awk {'print $1'}"))) * 1024
        MEMORY_CACHED_BYTES = (int(system_command("cat /proc/meminfo |grep Cached|awk -F\: {'print $2'}|awk {'print $1'}|head -n 1"))) * 1024
        MEMORY_ACTIVE_BYTES = (int(system_command("cat /proc/meminfo |grep Active|awk -F\: {'print $2'}|awk {'print $1'}"))) * 1024
        SWAP_TOTAL_BYTES = (int(system_command("cat /proc/meminfo |grep SwapTotal|awk -F\: {'print $2'}|awk {'print $1'}"))) * 1024
        SWAP_FREE_BYTES = (int(system_command("cat /proc/meminfo |grep SwapFree|awk -F\: {'print $2'}|awk {'print $1'}"))) * 1024
        
    elif SYSTEM_OS == "Darwin":
        CPU_MODEL = strrep(system_command("sysctl machdep.cpu.brand_string |awk -F\: {'print $2'}|tail -n 1").strip())
        CPUSPEEDOUT = round(int(strrep(system_command("sysctl hw.cpufrequency_max |awk -F\: {'print $2'}|tail -n 1").strip())))
        CPU_SPEED = CPUSPEEDOUT / 1000000
        MEMORY_TOTAL_BYTES = int(system_command("sysctl hw.memsize |awk -F\: {'print $2'}|tail -n 1"))
        MEMORY_FREE_BYTES = 0
        MEMORY_CACHED_BYTES = 0
        MEMORY_ACTIVE_BYTES = 0
        SWAP_TOTAL_BYTES = 0
        SWAP_FREE_BYTES = 0

    elif SYSTEM_OS == "FreeBSD" or "OpenBSD":
        CPU_MODEL = strrep(system_command("sysctl hw.model |awk -F\: {'print $2'}|tail -n 1").strip())
        CPU_SPEED = strrep(system_command("sysctl dev.cpu.0.freq |awk -F\: {'print $2'}|tail -n 1").strip())
        MEMORY_TOTAL_BYTES = strrep(system_command("sysctl hw.physmem |awk -F\: {'print $2'}|tail -n 1").strip())
        MEMORY_FREE_BYTES = 0
        MEMORY_CACHED_BYTES = 0
        MEMORY_ACTIVE_BYTES = 0
        SWAP_TOTAL_BYTES = 0
        SWAP_FREE_BYTES = 0

    #display info
    logger("MYSQL VERSION: %s"%(MYSQL_VERSION),"i")
    logger("INNODB BUFFER POOL SIZE: %s"%(MYSQL_INNODB_BUFFER_POOL_SIZE),"i")
    logger("INNODB FLUX LOG AT TX COMMIT LEVEL: %s"%(MYSQL_INNODB_FLUSH_TX),"i")
    logger("SYNC BINLOG: %s"%(MYSQL_SYNC_BINLOG),"i")
    logger("TX ISOLATION: %s"%(MYSQL_TX_ISOLATION),"i")
    if SYSTEM_OS == "Linux":
        logger("CPU MODEL: %s"%(CPU_MODEL),"i")
        logger("CPU SPEED: %s"%(CPU_SPEED),"i")
        logger("CPU CORES: %s"%(CPU_QUANT),"i")
        logger("MEM TOTAL BYTE: %s"%(MEMORY_TOTAL_BYTES),"i")
        logger("MEM FREE BYTE: %s"%(MEMORY_FREE_BYTES),"i") 
        logger("MEM CACHED BYTE: %s"%(MEMORY_CACHED_BYTES),"i")
        logger("MEM ACTIVE BYTE: %s"%(MEMORY_ACTIVE_BYTES),"i")
        logger("SWAP TOTAL BYTE: %s"%(SWAP_TOTAL_BYTES),"i")
        logger("SWAP FREE BYTE: %s"%(SWAP_FREE_BYTES),"i")
    logger("OS: %s"%(SYSTEM_OS),"i")
    logger("KERNEL: %s"%(SYSTEM_KERNEL),"i")
    logger("ARCH: %s"%(SYSTEM_ARCH),"i")
    logger("CPU_QUANT: %s"%(CPU_QUANT),"i")
    logger("THREADS: %i"%(THREADS),"i")

    #start threads for insert performance
    INSERT_OLTP_YES = 0
    INSERT_OLTP_NO = 0

    if mysql_oltp == False: #no transactions 
        start = time.time()
        init_thread("insert",0)
        end = time.time()
        timing = end - start
        INSERT_OLTP_NO = insert_quant / float(timing)
        logger("INSERT quantity: %i"%(insert_quant),"i")
        logger("INSERT timing : %s"%(timing),'i')
        logger("INSERT non-transactional peformance : %i /sec"%(INSERT_OLTP_NO),'i')

    else: 
        start = time.time()
        init_thread("insert",1)
        end = time.time()
        timing = end - start
        INSERT_OLTP_YES = insert_quant / float(timing)
        logger("INSERT quantity: %i"%(insert_quant),"i")
        logger("INSERT timing: %s seconds"%(round(timing,2)),'i')
        logger("INSERT transaction peformance: %i /sec"%(INSERT_OLTP_YES),'i')

    #SELECT INDEXED SEQUENTIAL
    SELECT_INDEX_YES_SEQ = 0
    SELECT_INDEX_YES_RAND = 0
    SELECT_INDEX_NO_SEQ = 0
    SELECT_INDEX_NO_RAND = 0

    start = time.time()
    init_thread("select_index_yes_seq",0)
    end = time.time()
    timing = end - start
    SELECT_INDEX_YES_SEQ = (select_quant / 2) / float(timing)
    logger("SELECT_INDEX_YES_SEQ quantity: %i"%(insert_quant),"i")
    logger("SELECT_INDEX_YES_SEQ timing: %s seconds"%(round(timing,2)),'i')
    logger("SELECT_INDEX_YES_SEQ transaction peformance: %i /sec"%(SELECT_INDEX_YES_SEQ),'i')

    #SELECT INDEXED RANDOM
    start = time.time()
    init_thread("select_index_yes_rand",0)
    end = time.time()
    timing = end - start
    SELECT_INDEX_YES_RAND = (select_quant / 2) / float(timing)
    logger("SELECT_INDEX_YES_RAND quantity: %i"%(insert_quant),"i")
    logger("SELECT_INDEX_YES_RAND timing: %s seconds"%(round(timing,2)),'i')
    logger("SELECT_INDEX_YES_RAND transaction peformance: %i /sec"%(SELECT_INDEX_YES_RAND),'i')
        
    if select_no_index == True:
        #SELECT NON-INDEXED SEQUENTIAL
        start = time.time()
        init_thread("select_index_no_seq",0)
        end = time.time()
        timing = end - start
        SELECT_INDEX_NO_SEQ = (select_quant / 2) / float(timing)
        logger("SELECT_INDEX_NO_SEQ quantity: %i"%(insert_quant),"i")
        logger("SELECT_INDEX_NO_SEQ timing: %s seconds"%(round(timing,2)),'i')
        logger("SELECT_INDEX_NO_SEQ transaction peformance: %i /sec"%(SELECT_INDEX_NO_SEQ),'i')

        #SELECT NON-INDEXED RANDOM
        start = time.time()
        init_thread("select_index_no_rand",0)
        end = time.time()
        timing = end - start
        SELECT_INDEX_NO_RAND = (select_quant / 2) / float(timing)
        logger("SELECT_INDEX_NO_RAND quantity: %i"%(insert_quant),"i")
        logger("SELECT_INDEX_NO_RAND timing: %s seconds"%(round(timing,2)),'i')
        logger("SELECT_INDEX_NO_RAND transaction peformance: %i /sec"%(SELECT_INDEX_NO_RAND),'i')
        
    else:
        logger("SELECT_INDEX_NO_SEQ quantity: NULL","i")
        logger("SELECT_INDEX_NO_SEQ timing: %s seconds: NULL",'i')
        logger("SELECT_INDEX_NO_SEQ transaction peformance: NULL",'i')
        logger("SELECT_INDEX_NO_RAND quantity: NULL","i")
        logger("SELECT_INDEX_NO_RAND timing: %s seconds: NULL",'i')
        logger("SELECT_INDEX_NO_RAND transaction peformance: NULL",'i')

    #connect to remote db and insert performance
    url="%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s"%(update_url,
                                                                                      MYSQL_VERSION,
                                                                                      MYSQL_INNODB_BUFFER_POOL_SIZE,
                                                                                      MYSQL_SYNC_BINLOG,
                                                                                      MYSQL_TX_ISOLATION,
                                                                                      CPU_MODEL,
                                                                                      CPU_SPEED,                                                                      
                                                                                      CPU_QUANT,
                                                                                      MEMORY_TOTAL_BYTES,
                                                                                      MEMORY_FREE_BYTES,
                                                                                      MEMORY_CACHED_BYTES,
                                                                                      MEMORY_ACTIVE_BYTES,
                                                                                      SWAP_TOTAL_BYTES,
                                                                                      SWAP_FREE_BYTES,
                                                                                      SYSTEM_OS,
                                                                                      SYSTEM_KERNEL,
                                                                                      SYSTEM_ARCH,
                                                                                      INSERT_OLTP_YES,
                                                                                      INSERT_OLTP_NO,
                                                                                      SELECT_INDEX_YES_SEQ,
                                                                                      SELECT_INDEX_YES_RAND,
                                                                                      SELECT_INDEX_NO_SEQ,
                                                                                      SELECT_INDEX_NO_RAND,
                                                                                      THREADS,
                                                                                      MYSQL_INNODB_FLUSH_TX)

    print url
    try:
        urllib2.urlopen(url)
        closedb()
    except:
        logger("Failed to insert benchmark","i")
        closedb()
        sys.exit(127)
        
    sys.exit(0)

if __name__ == "__main__":
    mysql_oltp = True #default True
    mysql_host = "localhost" #default localhost
    mysql_pass = "dbbench" #default dbbench
    mysql_user = "dbbench" #default dbbench
    mysql_port = 3306 #default 3306
    mysql_db = "dbbench" #default dbbench
    mysql_socket_timeout = 5 #default timeout to 5 seconds
    insert_quant = 1000 #default 50000
    select_quant = 100 #default 500
    select_no_index = True #default False
    update_url = "http://dbbenchmark.com/db/index.php/incoming/add" #no trailing slash
    global THREADS
    global SYSTEM_OS
    global CPU_QUANT

    #calculate the default number of threads based on cores (quantity * 2)
    #get system type
    retcode, output = commands.getstatusoutput("uname -s")
    if retcode != 0:
        retcode = str(retcode)
        print "Failed to read OS type. Error: %s"%(retcode)
        sys.exit(1)
    else:
        SYSTEM_OS = output
    
    if SYSTEM_OS == "Linux":
        cmd = "cat /proc/cpuinfo |grep 'model name'|awk -F\: {'print $2'}|wc -l"
    elif SYSTEM_OS == "FreeBSD" or "OpenBSD":
        cmd = "sysctl hw.ncpu |awk -F\: {'print $2'}|tail -n 1"
    elif SYSTEM_OS == "Darwin":
        cmd = "sysctl hw.ncpu |awk -F\: {'print $2'}|tail -n 1"
        
    retcode, output = commands.getstatusoutput(cmd)
    if retcode != 0:
        retcode = str(retcode)
        print "Failed to find CPU core quantity. Error: %s"%(retcode)
        sys.exit(1)
    else:
        CPU_QUANT = output.strip()
        THREADS = int(CPU_QUANT)
                        
    try:
        options, remainder = getopt.getopt(
            sys.argv[1:], '', ['mysql-host=',
                               'mysql-pass=',
                               'mysql-user=',
                               'mysql-port=',
                               'mysql-db=',
                               'mysql-timeout=',
                               'mysql-no-tx',
                               'insert-quant=',
                               'select-quant=',
                               'select_no_index',
                               'threads=',
                               'update-url=',
                               'print-sql',
                               'help'])
    except getopt.GetoptError, err:
        print str(err) 
        sys.exit(2)
        
    for opt, arg in options:
        if opt in ('--mysql-host'):
            mysql_host = arg            
        elif opt in ('--mysql-pass'):
            mysql_pass = arg        
        elif opt in ('--mysql-user'):
            mysql_user = arg
        elif opt in ('--mysql-port'):
            mysql_port = int(arg)
        elif opt in ('--mysql-db'):
            mysql_db = arg
        elif opt in ('--mysql-timeout'):
            mysql_socket_timeout = int(arg)
        elif opt in ('--mysql-no-tx'):
            mysql_oltp = False
        elif opt in ('--insert-quant'):
            insert_quant = int(arg)
        elif opt in ('--select-quant'):
            select_quant = int(arg)
        elif opt in ('--select_no_index'):
            select_no_index = True
        elif opt in ('--threads'):
            THREADS = int(arg)
        elif opt in ('--update-url'):
            update_url = arg
        elif opt in ('--print-sql'):
            print_sql()
            sys.exit(2)
        elif opt in ('--help'):
            print_help()
            sys.exit(2)
            
    #create log instance
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    c = logging.StreamHandler(sys.stdout)
    c.setLevel(logging.INFO)
    c.setFormatter(formatter)
    log.addHandler(c)
    #end log creation

    print '''+++++++++++++++++++++++++++++++++++
Running with the following settings:
mysql-host: %s
mysql-user: %s
mysql-pass: %s
mysql-port: %i
mysql-db: %s
mysql-timeout: %i
mysql-oltp: %s
threads: %i
+++++++++++++++++++++++++++++++++++'''%(mysql_host,
                                        mysql_user,
                                        mysql_pass,
                                        mysql_port,
                                        mysql_db,
                                        mysql_socket_timeout,
                                        mysql_oltp,
                                        THREADS)

    check_port(mysql_port)
    #create initial db connection for general operations
    try:
        initdb = MySQLdb.connect(host=mysql_host, user=mysql_user, passwd=mysql_pass, db=mysql_db, port=mysql_port)
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)

    #create connection pool
    connections = []
    for thread in range(THREADS):
        try:
            connections.append(MySQLdb.connect(host=mysql_host, user=mysql_user, passwd=mysql_pass, db=mysql_db, port=mysql_port))
        except MySQLdb.Error, e:
            print "Error %d: %s"%(e.args[0], e.args[1])
            sys.exit (1)                        
    main()







